package tree.reader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import tree.model.Node;
import tree.person.Person;

public class TreeReader {
	
	Map<Long, Node<Person>> nodesMap = new TreeMap<Long, Node<Person>>();
	
	public TreeReader(){
	}
	
	public List<Node<Person>>read(boolean lazy){
		StaXParser read = new StaXParser();
		List<Person> readConfig = read.readConfig("tree.xml", lazy);
		List<Node<Person>> nodes = new ArrayList<Node<Person>>();
		
		
		for (Person person : readConfig) {
			Node<Person> node = new Node<Person>(person.getId());
			node.setData(person);
			nodes.add(node);
		}
		
		
		for (Node<Person> node : nodes) {
			long momId = node.getData().getMumId();
			long dadId = node.getData().getDadId();
			node.setLeft(nodesMap.get(momId));
			node.setRight(nodesMap.get(dadId));
		}
		
		return nodes;
	}
	
	public Node<Person> getRoot(){
		Node<Person> root=null;
		
		
		Set<Long> keys = nodesMap.keySet();
		long max = 0;
		for (Long l : keys) {
			if(l>max){
				max = l;
			}
		}
		
		root = nodesMap.get(max);
		return root; 
	}

}
